#include "shmem.h"

/*
	Receiver function
	Initialises all Ressources and receives signs one by one
	EOF problem is solved with using ints intstead of chars, to use additional EOF value
	Cleanup at the end to remove all used ressources
*/
int main (int argc, char *argv[])
{
    /* Buffer of SHM */
    int shm_buffer = 0;

    /* Char as int representation, to include EOF */
    int input_sign = -1;
 
    /* Check and Convert Command Line Parameters */
    if ((shm_buffer = CheckParams(argc, argv)) == -1) 
		return ERROR;
 
    /* Initialises ressources (SHM, Semaphores) */
    if (InitResources(RECEIVER, shm_buffer) == -1) 
		return ERROR;
 
    /* Start to read form shared memory */
    do {
     
			/* Wait for the read semaphore */
			if (WaitForSemaphore() == -1) 
			return ERROR;
 
			/* Write to SHM */
			input_sign = ReadFromSharedMemory(); 
       
			/* Signal to write semaphore */
			if (SignalToSemaphore() == -1) 
			return ERROR;

			 /* Output chars (as int), without EOF !*/
			if (input_sign != EOF)
				{
					if (fputc(input_sign, stdout) == EOF) 
					{
						handle_errno("Error writing to stdout!");
						return ERROR;
					}
				}
			if (errno == EINTR)
			  {
			    break;
			  }
		} while (input_sign != EOF);

    /* CI_FB: Hier fehlt das flushen des stdout, welcher buffered ist */
    /* Cleanup (SHM, Semaphores) and return exit state */
    if (clean_up(SEM_R_KEY) == -1)
		return ERROR;
    else                            
		return OKAY;
}
